<!doctype html>
<html lang="{{ config('app.locale') }}">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, viewport-fit=cover">
  <meta name="_token" content="{{ csrf_token() }}"/>
  <meta name="format-detection" content="telephone=no">

  <title>Qkids久趣英语</title>
  <script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/mobile/rem.js"></script>

  <link href="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/css/share.css?v={{config('app.version')}}" rel="stylesheet" type="text/css">

</head>

<body>
<img class="banner" src="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/img/banner-share.jpg" alt="banner"/>
<img class="play pulse" id="playVideo" src="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/img/play.png" alt="播放"/>

<div class="main">
  <div class="main-title">您的好友<span class="main-title-name"></span>邀你领取</div>
  <div class="given">
    <div class="given-left">
      <div class="given-left-title">四人班</div>
      <div class="given-left-desc">有效期14天</div>
      <span class="given-semicircle"></span>
      <span class="given-semicircle"></span>
    </div>
    <div class="given-right">
      <!-- <div class="given-right-title">免费课时</div> -->
      <div class="success-given-right-num">1</div>
        <div class="success-given-right-desc">课时</div>
    </div>
    <!-- <div class="got-num">1节</div> -->
  </div>
  <div class="receive">
    <div class="phone">
      <label for="phone" class="phone-label">手机号</label>
      <input type="tel" pattern="\d*" autofocus placeholder="输入手机号" id="phone" class="phone-input" maxlength="11"/>
    </div>
    <div>
      <div class="code">
        <label for="code" class="phone-label">验证码</label>
        <input type="tel" pattern="\d*" placeholder="输入验证码" id="code" class="code-input" maxlength="4"/>
      </div>
      <div class="send-code" id="send-code">发送验证码</div>
    </div>
    <div class="get" id="get">立即领取</div>
  </div>
  <div class="result">
    <div class="result-title">恭喜你，领取成功！</div>
    <div class="result-desc">免费课时已发放至
      <span class="account-get-phone"></span>的账户
    </div>
  </div>
  <div class="tips">
    <img class="tips-title" src="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/img/tips-title.jpg" alt="标题"/>
    <img class="tips-qr-code" src="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/img/qrcode2.jpg" alt="二维码"/>
    <div class="tips-item">
      <span class="tips-item-num">1</span>关注公众号『久趣英语服务号』
    </div>
    <div class="tips-item">
      <span class="tips-item-num">2</span>公众号点击『预约上课』，自主约课
    </div>
    <a class="tips-btn" href="https://mp.weixin.qq.com/s/52JgJyXuQwgz4dJd3vSZnQ">了解如何上课</a>
  </div>
</div>

<img class="intro" src="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/img/intro.png" alt="介绍"/>

<img class="logo" src="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/img/qkids.jpg" alt="logo"/>

<div class="email">企业邮箱 service@qkids.cn</div>
<img class="qr-code" src="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/img/qrcode.jpg" alt="二维码"/>
<div class="qr-name">久趣英语服务号</div>
<div class="account">
  当前账号：
  <span class="account-phone"></span>
  <span id="switch-account-share" class="switch-account">切换账号</span>
</div>

<div class="copy-right-warp">
  <div class="copy-right">
    <div class="copy-right-time">Copyright @2017-2018 Qkids All Rights Reserved</div>
    <div class="copy-right-num">闽ICP备12021838号-3</div>
  </div>
</div>

<div class="video-mask" id="videoMask">
  <div class="close-icon icon" id="closeVideo"></div>
  <div id="videoContainer" class="video">
  </div>
</div>
<div id="alertBox" class="alert-box"></div>
<div class="alert-wrap">
  <div class="alert">
    <div class="alert-title">设置约课密码</div>
    <input class="alert-input" type="password" id="pwd" placeholder="6～12位新密码，数字加字母"/>
    <div class="alert-btn alert-btn-disabled">完成</div>
  </div>
</div>

<!--引入微信js-SDK-->
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript" src=" {{env('CDN_RESOURCE')}}/js/mobile/wx_config.js?v={{config('app.version')}}"></script>
<script type="text/javascript" src="https://static-app.97kid.com/wx/js/zepto.min.js"></script>
<script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/mobile/Zepto_fx_methods.js"></script>
<script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/AV.analytics.js"></script>

<script type="text/javascript">
  (function ($) {
    $(function () {
      if (!getQueryString('_c')) {
        var QKidsChannel = JSON.parse(window.localStorage.getItem('QKidsChannel'))
        if (!(QKidsChannel && QKidsChannel.expires > new Date().getTime() / 1000)) {
          window.localStorage.setItem('QKidsChannel', JSON.stringify({
            rawData: 'invite_share',
            expires: new Date().getTime() / 1000 + 24 * 3600
          }))
        }
      }

      if (!getQueryString('_r')) {
        var QKidsReference = JSON.parse(window.localStorage.getItem('QKidsReference'))
        if (!(QKidsReference && QKidsReference.expires > new Date().getTime() / 1000)) {
          window.localStorage.setItem('QKidsReference', JSON.stringify({
            rawData: 'invite_share',
            expires: new Date().getTime() / 1000 + 24 * 3600
          }))
        }
      }

      window.analytics = AV.analytics({
        appId: 'antYy9lOFi5mkU9QKjtYmRLM-gzGzoHsz',
        appKey: 'jqyWxLyobpsmdwsJddJlDheb',
        channel: /(MicroMessenger)/i.test(navigator.userAgent) ? 'weixin' : ''
      })
      var glcode = getQueryString('glcode')

      // 分享码不能为空
      if (!glcode) {
        toastAlert('分享码不能为空')
        return
      }

      analytics.send({
        event: 'p006_get_pv',
        attr: {
          gid: glcode
        }
      })

      var token
      var isRequesting = false
      // 是否领取成功
      var isSuccessed = false
      // accept 请求是否完成 
      var isAccepted = false
      var reference = ''
      var channel = ''
      var friend = '久趣宝宝'
      var apiUrl = 'https://gate.97kid.com'
      var countdown = 60
      var configOption = {
        timestamp: '{{$signature['timestamp']}}',
        nonceStr: '{{$signature['nonceStr']}}',
        signature: '{{$signature['signature']}}',
        jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareQZone']
      }
      var shareFlag = ''

      var wxconfig = new WxConfig(configOption, 'invite')
      wxconfig.activeShare(shareFlag, '', shareMsg())
      
      checkLoginStatus()
            
      getID()

      // 设置约课密码
      $('.alert-btn').on('click', function (e) {
        var pwd = $('#pwd').val()
        if (!checkPassword(pwd, true)) return false
        if (isRequesting) return
        isRequesting = true
        setPassword(pwd)
      })

      $("#pwd").on('input', function (e) {
        var pwd = $('#pwd').val()
        if (!checkPassword(pwd, false)){
          $(".alert-btn").addClass("alert-btn-disabled");
        }else {
          $(".alert-btn").removeClass("alert-btn-disabled");
        }
      })
      $("#pwd").on('change', function (e) {
        var pwd = $('#pwd').val()
        if (!checkPassword(pwd, false)){
          $(".alert-btn").addClass("alert-btn-disabled");
        }else {
          $(".alert-btn").removeClass("alert-btn-disabled");
        }
      })

      // 发送验证码
      $('#send-code').on('click', function () {
        if (countdown !== 60) return

        var mobile = $.trim($('#phone').val())

        if (!checkMobile(mobile)) return false
        if (isRequesting) return
        isRequesting = true
        sendCode()
      })

      // 立即领取
      $('#get').on('click', function (e) {
        login()
      })

      // 切换账号
      $('#switch-account-share').on('click', function (e) {
        $('#phone').val('')
        $('#code').val('')
        $('.given').removeClass('given-fail')
        $('.account').css({'display': 'none'})
        $('.receive').css({'display': 'block'})
        $('.result').css({'display': 'none'})
        $('.tips').css({'display': 'none'})
        $('.account-phone').text('')
        // 滚动到顶部
        $('.main')[0].scrollIntoView ? $('.main')[0].scrollIntoView() : document.body.scrollTop = 110;


      })

      try {
        var referenceObj = JSON.parse(window.localStorage.getItem('QKidsReference'))
        if (referenceObj && referenceObj.rawData && new Date().getTime() / 1000 < referenceObj.expires) {
          reference = referenceObj.rawData
        }
      } catch (e) {
        console.log(e)
      }

      try {
        var channelObj = JSON.parse(window.localStorage.getItem('QKidsChannel'))
        if (channelObj && channelObj.rawData && new Date().getTime() / 1000 < channelObj.expires) {
          channel = channelObj.rawData
        }
      } catch (e) {
        console.log(e)
      }

      // 检查登录状态
      function checkLoginStatus() {
        var accessString = window.localStorage.getItem('QKidsAccess')
        if (!accessString) return 
        var access = JSON.parse(accessString)
        token = access.access_token
        var expireAt = access.expire_at
        var refreshToken = access.refresh_token

        if (new Date().getTime() / 1000 < expireAt) {
          accept()
          getUserInfo()
        } else {
          $.ajax({
            type: 'POST',
            url: apiUrl + '/s/user/refresh',
            data: JSON.stringify({
              refresh_token: refreshToken
            }),
            contentType: 'application/json',
            success: function (result) {
              token = result.access_token
              saveToken(result)
              accept()
              getUserInfo()
            },
            error: function (err) {
              alertErrorMsg(err)
            }
          })
        }
      }
      
      // 保存登录信息
      function saveToken (data) {
        var tokenObj = {}
        tokenObj.access_token = data.access_token
        tokenObj.expires_in = data.expires_in
        tokenObj.token_type = data.token_type
        tokenObj.refresh_token = data.refresh_token
        token = tokenObj.access_token
        tokenObj.expire_at = new Date().getTime() / 1000 + tokenObj.expires_in - 600

        window.localStorage.setItem('QKidsAccess', JSON.stringify(tokenObj))
      }

      function getUserInfo() {
        $.ajax({
          type: 'GET',
          url: apiUrl + '/s/user',
          headers: {'Authorization': 'Bearer ' + token},
          contentType: 'application/json',
          success: function (result) {
            window.localStorage.setItem('QKidsUserInfo', JSON.stringify(result))

            if(result.mobile){
              $('.account-phone').text(result.mobile.replace(/^(\d{3})\d{4}(\d+)/, '$1****$2'))
              $('.account').css({"display": "block"})
              if(!isAccepted || (isAccepted && isSuccessed)){
                $('.result-desc').text('免费课时已发放至' + result.mobile.replace(/^(\d{3})\d{4}(\d+)/, '$1****$2') + '的账户')
              }
            }
            
          },
          error: function (err) {
            alertErrorMsg(err)
          }
        })
      }

      // 分享设置信息
      function shareMsg () {
        return {
          title: '来自' + friend + ': 送你1节孩子最爱的北美外教课，免费哟~',
          desc: '快来跟我们做同学吧~ ',
          link: window.location.protocol + '//' + window.location.host + '/wx/invite/share?_c=invite_share&_r='+ shareFlag +'&glcode=' + glcode,
          imgUrl: 'https://static-app.97kid.com/site-student/public/img/share.png',
          success: function (target) {
            analytics.send({
              event: 'p006_get_share_success',
              attr: {
                gid: glcode,
                target: target
              }
            })
          }
        }
      }

      // toast错误信息
      function alertErrorMsg (data) {
        var error
        if (data && data.response) {
          error = JSON.parse(data.response)
        }
        if (error && error.message) {
          toastAlert(error.message)
        }
      }

      // 根据id获取昵称
      function getNickname (id) {
        $.ajax({
          type: 'GET',
          url: apiUrl + '/s/students/socials',
          data: {ids: id},
          contentType: 'application/json',
          success: function (data) {
            if (data && data.length > 0) friend = data[0].nickname || '你的朋友'
            $('.main-title-name').text(friend)
            wxconfig.activeShare(shareFlag, '', shareMsg())
          },
          error: function (data) {
            alertErrorMsg(data)
          }
        })
      }

      // toast message
      function toastAlert (msg) {
        var $box = $('#alertBox')
        $box.html(msg)
        $box.fadeIn()

        setTimeout(function () {
          $box.fadeOut()
        }, 3000)
      }

      // 设置密码
      function setPassword (pwd) {
        $.ajax({
          type: 'POST',
          url: apiUrl + '/s/user/password',
          data: JSON.stringify({password: pwd}),
          headers: {'Authorization': 'Bearer ' + token},
          contentType: 'application/json',
          success: function (data) {
            $('.alert-wrap').css({'display': 'none'})
            accept()
          },
          error: function (data) {
            alertErrorMsg(data)
            isRequesting = false
          }
        })
      }

      // 检查密码
      function checkPassword (password, isAlert) {
        //字段值仅允许字母、数字、破折号（-）以及底线（_）
        var pregPassword = /^[0-9A-Za-z_-]{6,30}$/
        if (password === '' || password.length < 6 || password.length > 32) {
          if(isAlert) {
            toastAlert('密码长度为6-32位')
          }
          return false
        }

        if (!pregPassword.test(password)) {
          if(isAlert) {
            toastAlert('密码长度6到10位,仅允许字母，数字，破折号，底线 ')
          }
          return false
        }
        return true
      }

      // 解析url查询参数
      function getQueryString (name) {
        var r1 = getMatched(name, window.location.search)
        if (r1) return r1
        var key = arguments[1]
        if (key) {
          return getMatched(name, window.localStorage.getItem(key))
        }
        return null

        function getMatched (name, string) {
          if (string) {
            var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
            var len = string.indexOf('?') == 0 ? 1 : 0
            var r = string.substr(len).match(reg)
            if (r != null) return unescape(r[2])
          }
          return null
        }
      }

      // 根据glcode获取ID
      function getID () {
        $.ajax({
          type: 'GET',
          url: apiUrl + '/s/events/giftLesson/public',
          data: {code: glcode},
          contentType: 'application/json',
          success: function (data) {
            const id = data.studentId
            getNickname(id)
          },
          error: function (data) {
            alertErrorMsg(data)
          }
        })
      }

      // 检查手机号
      function checkMobile (mobile) {
        var pregMobile = /^1\d{10}$/
        if ($.trim(mobile) === '') {
          toastAlert('手机号不能为空', 2)
          return false
        }

        if (!pregMobile.test(mobile)) {
          toastAlert('不是有效的手机号', 2)
          return false
        }
        return true
      }

      //启动计时器
      function setTime (obj) {
        if (countdown === 0) {
          obj.attr('disabled', false)
          obj.text('发送验证码')
          countdown = 60
          obj.removeClass("send-code-disabled")
          return
        } else {
          obj.attr('disabled', false)
          obj.text('重新发送(' + countdown + 's)')
          obj.addClass("send-code-disabled")
        }
        countdown--

        setTimeout(function () {
          setTime(obj)
        }, 1000)
      }

      // 手机号登录
      function login () {
        var phone = $('#phone').val()
        var code = $('#code').val()
        if(phone === '') {
          toastAlert('手机号不能为空')
          return false
        }
        if (!checkMobile(phone)) {
          toastAlert('请输入正确的手机号')
          return false
        }
        if(code === '') {
          toastAlert('验证码不能为空')
          return false
        }
        if(code.length !== 4) {
          toastAlert('请输入正确的验证码')
          return false
        }
        if (isRequesting) return
        isRequesting = true
        $.ajax({
          type: 'POST',
          url: apiUrl + '/s/user/login/sms',
          data: JSON.stringify({
            mobile: phone,
            smsCode: code,
            reference: reference,
            channel: channel
          }),
          contentType: 'application/json',
          success: function (data) {
            token = data.access_token
            saveToken(data)
            if (data.isPasswordSet) {
              accept()
            } else {
              $('.alert-wrap').css({'display': 'flex'})
              isRequesting = false
            }
         
            $('.account-phone').text(phone.replace(/^(\d{3})\d{4}(\d+)/, '$1****$2'))
            $('.account').fadeIn()

          },
          error: function (data) {
            alertErrorMsg(data)
            isRequesting = false
          }
        })
      }

      // 接受邀请
      function accept () {
        $.ajax({
          type: 'POST',
          url: apiUrl + '/s/events/giftLesson/accept',
          data: JSON.stringify({code: glcode}),
          headers: {'Authorization': 'Bearer ' + token},
          contentType: 'application/json',
          success: function (data) {
            var phone = $('#phone').val()

            if (data && data.status === 'created') {
              $('.given').removeClass('given-fail')
              $('.result-title').text('恭喜您，领取成功！')
              if(phone) {
                $('.result-desc').text('免费课时已发放至' + phone.replace(/^(\d{3})\d{4}(\d+)/, '$1****$2') + '的账户')
              }
              $('.tips-btn').text('了解如何上课')
              $('.tips-btn').attr('href', 'https://mp.weixin.qq.com/s/52JgJyXuQwgz4dJd3vSZnQ')
              $('.tips-title').css({'display': 'block'})
              $('.tips-item').css({'display': 'block'})
              $('.receive').css({'display': 'none'})
              $('.result').css({'display': 'block'})
              $('.tips').css({'display': 'block'})
              isSuccessed = true
              analytics.send({
                event: 'p006_get_success',
                attr: {
                  gid: glcode
                }
              })
            }
            isRequesting = false
            isAccepted = true;
          },
          error: function (data) {
            var error
            if (data && data.response) {
              error = JSON.parse(data.response)
            }
            $('.given').addClass('given-fail')
            $('.result-desc').text(error.message)
            $('.receive').css({'display': 'none'})

            if (error && error.code === 'gift.lesson.invalid.acceptance') {
              $('.result-title').text('很抱歉，未能成功领取')
              analytics.send({
                event: 'p006_get_old_fial',
                attr: {
                  gid: glcode
                }
              })
            } else {
              $('.result-title').text('很遗憾，您来晚了')
              $('.tips-title').css({'display': 'none'})
              $('.tips-item').css({'display': 'none'})
              $('.tips-btn').text('了解更多优惠')
              $('.tips-btn').attr('href', '//wx2.97kid.com/wx')

              $('.tips').css({'display': 'block'})
              analytics.send({
                event: 'p006_get_new_fail',
                attr: {
                  gid: glcode
                }
              })
            }

            $('.result').css({'display': 'block'})

            isRequesting = false
            isAccepted = true;

          }
        })
      }

      // 发送验证码
      function sendCode () {
        $.ajax({
          type: 'POST',
          url: apiUrl + '/s/user/sms/login',
          data: JSON.stringify({mobile: $('#phone').val()}),
          contentType: 'application/json',
          success: function (data) {
            setTime($('#send-code'))
            toastAlert('验证码已经发送')
            isRequesting = false
          },
          error: function (data) {
            alertErrorMsg(data)
            isRequesting = false
          }
        })
      }

      // 注销登录
      // function signOut () {
      //   $.ajax({
      //     type: 'GET',
      //     url: apiUrl + '/s/user/logout',
      //     headers: {'Authorization': 'Bearer ' + token},
      //     contentType: 'application/json',
      //     success: function (data) {
      //       $('#phone').val('')
      //       $('#code').val('')
      //       $('.given').removeClass('given-fail')
      //       $('.account').css({'display': 'none'})
      //       $('.receive').css({'display': 'block'})
      //       $('.result').css({'display': 'none'})
      //       $('.tips').css({'display': 'none'})
      //       window.localStorage.setItem('QKidsAccess', '')
      //       token = null
      //       $('.account-phone').text('')
      //       toastAlert('退出成功')
      //       isRequesting = false
      //     },
      //     error: function (data) {
      //       alertErrorMsg(data)
      //       isRequesting = false
      //     }
      //   })
      // }
    })
  })(window.Zepto)
</script>

@include('mobile.partial.video', [
  'prefix' => 'p006',
  'finishTime' => '110',
  'videoOption' => [
    'm3u8' => 'http://1251352844.vod2.myqcloud.com/45f5686avodtransgzp1251352844/3b4dc3f34564972818953227732/v.f20.mp4',
    'autoplay' => false,
    'coverpic' => '',
    'width' => '640',
    'height' => '480',
    'live' => false,
    'systemFullscreen' => true
  ]
])
</body>

</html>